package com.zb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.ZjAdmRole;
import com.zb.entity.dto.RoleDto;
import com.zb.entity.dto.RoleList;
import com.zb.entity.dto.RoleSelect;
import com.zb.exception.RegisterException;
import com.zb.mapper.ZjAdmRoleMapper;
import com.zb.service.ZjAdmRoleService;
import com.zb.utils.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台角色表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-07-07
 */
@Service
public class ZjAdmRoleServiceImpl extends ServiceImpl<ZjAdmRoleMapper, ZjAdmRole> implements ZjAdmRoleService {
    @Autowired
    private ZjAdmRoleMapper admRoleMapper;

    // 添加或修改角色
    @Override
    public void add(RoleDto roleDto) throws RegisterException {
        if (null != admRoleMapper.existByName(roleDto.getId(), roleDto.getName())) {
            throw new RegisterException("角色已重复！");
        }
        if (null != admRoleMapper.existByCode(roleDto.getId(), roleDto.getCode())) {
            throw new RegisterException("角色编码已重复！");
        }
        ZjAdmRole role = new ZjAdmRole();
        BeanUtils.copyProperties(roleDto, role);
        if (null != role.getId()) {
            this.updateById(role);
            return;
        }
        role.setId(IdWorker.getId());
        role.setAdmin(false);
        this.save(role);
    }

    // 角色列表查询
    @Override
    public Map<String, Object> getList(RoleSelect roleSelect) {
        QueryWrapper<ZjAdmRole> wrapper = new QueryWrapper();
        wrapper.orderByDesc("gmt_update");
        if (StringUtils.isNotBlank(roleSelect.getName())) {
            wrapper.like("name", roleSelect.getName());
        }
        PageUtil.setPageLimit(roleSelect);
        Page<ZjAdmRole> page = this.page(new Page<>(roleSelect.getPage(), roleSelect.getLimit()), wrapper);

        List<RoleList> roleLists = new ArrayList<>();
        page.getRecords().forEach(t -> roleLists.add(RoleList.beanToRole(t)));
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), roleLists);
    }
}
